package com.gaka.only;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class Client {
	
	public String getData(String user) throws ClientProtocolException, IOException{
		HttpClient httpclient = new DefaultHttpClient();
		// force strict cookie policy per default
		httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);

		HttpGet httpget = new HttpGet("http://news.rhea.media.daum.net/rhea/do/social/json/commentListByUser?cPageIndex=1&userId=JIKz4J6sNLM0");
		// Override the default policy for this request
		httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
		httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpget.addHeader("Accept-Charset", "EUC-KR,utf-8;q=0.7,*;q=0.7");
		httpget.addHeader("Accept-Encoding", "gzip, deflate");
		httpget.addHeader("Accept-Language", "ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3");
		httpget.addHeader("Connection", "keep-alive");
		httpget.addHeader("Host", "news.rhea.media.daum.net");
		httpget.addHeader("User-Agent", "User-Agent	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
				
		HttpContext localContext = new BasicHttpContext();

		HttpResponse response = httpclient.execute(httpget, localContext);
		
		HttpEntity entity = response.getEntity();
		StringBuilder result = new StringBuilder();

		if (entity != null) {
		    InputStream is = entity.getContent();
		    BufferedReader br = new BufferedReader(new InputStreamReader(is));
		    
		    try {
		    	String line = null;
		    	while((line = br.readLine()) != null){
		    		System.out.println(line);
		    		result.append(line);
		    	}
		    } finally {
		    	is.close();
		    }
		}
		
//		Header[] headers = response.getAllHeaders();
//		for(Header header : headers){
//			System.out.println(header.toString());
//		}
//		System.out.println(response.getProtocolVersion());
//		System.out.println(response.getStatusLine().getStatusCode());
//		System.out.println(response.getStatusLine().getReasonPhrase());
//		System.out.println(response.getStatusLine().toString());
		
		return result.toString();
	}
}
